package com.learn.shop.job;

import com.learn.shop.mapper.TaskHistoryMapper;
import com.learn.shop.pojo.entriy.CrawlingNovelData;
import com.learn.shop.pojo.entriy.TaskHistory;
import com.learn.shop.pojo.vo.BatchCrawlingNovelVo;
import com.learn.shop.pojo.vo.CrawlingNovelVo;
import com.learn.shop.service.CrawlingNovelDataService;
import com.learn.shop.service.CrawlingNovelService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.Set;

@Component
@Slf4j
public class TaskJob {

    private static final Logger logger = LoggerFactory.getLogger(TaskJob.class);

    @Autowired
    @Qualifier("CrawlingNovelImplV3")
    private CrawlingNovelService crawlingNovelService;

    @Autowired
    private CrawlingNovelDataService dataService;

    @Autowired
    private MongoTemplate mongoTemplate;

    @SuppressWarnings("all")
    @Autowired
    private TaskHistoryMapper taskHistoryMapper;

    // 添加定时任务
//    @Scheduled(cron = "0 0 0/1 * * ?") // cron 表达式，每隔1小时 执行一次
    @XxlJob("getNovelHandler")
    public void doTask() {
        TaskHistory taskHistory = taskHistoryMapper.selectNewOperation();
        if (taskHistory != null) {
            String operation = taskHistory.getOperation();
            if ("1".equals(operation)) {
                logger.info("定时任务开始执行...");
                Set<String> collectionNames = mongoTemplate.getCollectionNames();
                BatchCrawlingNovelVo novelVo = new BatchCrawlingNovelVo();
                novelVo.setNovelName(collectionNames);
                novelVo.setCount(5);

                List<CrawlingNovelData> list = dataService.list(novelVo);

                for (CrawlingNovelData crawlingNovelData : list) {
                    CrawlingNovelVo crawlingNovelVo = new CrawlingNovelVo();
                    crawlingNovelVo.setNovelName(crawlingNovelData.getNovelName());
                    crawlingNovelVo.setUrl(crawlingNovelData.getUrl());
                    crawlingNovelVo.setUrlSplit("la");
                    try {
                        crawlingNovelService.novel(crawlingNovelVo);
                    } catch (IOException e) {
                        e.printStackTrace();
                        logger.error("定时任务爬取小说-->解析HTML出错");
                    }
                }
                logger.info("定时任务执行结束...");
            }

        }

    }

    @XxlJob("testHandler")
    public void test(){
        System.out.println("@@@@xxl-job定时测试任务--->执行啦!!!");
    }
}
